package handlers

import (
	"net/http"
	"time"

	"dormitory/database"
	"dormitory/models"

	"github.com/gin-gonic/gin"
)

// GetRepairRequests 获取维修申请列表
func GetRepairRequests(c *gin.Context) {
	status := c.Query("status")  // 可选的状态筛选
	roomNo := c.Query("room_no") // 可选的宿舍号筛选

	var requests []models.RepairRequest
	query := database.DB

	// 根据条件筛选
	if status != "" {
		query = query.Where("status = ?", status)
	}
	if roomNo != "" {
		query = query.Where("room_no = ?", roomNo)
	}

	// 按创建时间倒序排序
	result := query.Order("created_at desc").Find(&requests)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取维修申请列表失败"})
		return
	}

	c.JSON(http.StatusOK, requests)
}

// CreateRepairRequest 创建新的维修申请
func CreateRepairRequest(c *gin.Context) {
	var request models.RepairRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
		return
	}

	// 验证宿舍是否存在
	var dormitory models.Dormitory
	if err := database.DB.Where("room_no = ?", request.RoomNo).First(&dormitory).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "宿舍不存在"})
		return
	}

	// 验证学生是否存在且属于该宿舍
	var student models.Student
	if err := database.DB.Where("student_id = ? AND room_no = ?", request.StudentID, request.RoomNo).First(&student).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "该学生不属于此宿舍"})
		return
	}

	// 设置初始状态和学生姓名
	request.Status = models.StatusPending
	request.StudentName = student.Name

	result := database.DB.Create(&request)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建维修申请失败"})
		return
	}

	c.JSON(http.StatusCreated, request)
}

// GetRepairRequest 获取单个维修申请详情
func GetRepairRequest(c *gin.Context) {
	id := c.Param("id")
	var request models.RepairRequest

	result := database.DB.First(&request, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "维修申请不存在"})
		return
	}

	c.JSON(http.StatusOK, request)
}

// UpdateRepairRequest 更新维修申请状态
func UpdateRepairRequest(c *gin.Context) {
	id := c.Param("id")
	var request models.RepairRequest

	// 检查维修申请是否存在
	if err := database.DB.First(&request, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "维修申请不存在"})
		return
	}

	// 获取更新数据
	var updateData struct {
		Status  models.RepairStatus `json:"status"`
		Comment string              `json:"comment"`
	}
	if err := c.ShouldBindJSON(&updateData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
		return
	}

	// 更新状态和处理意见
	updates := map[string]interface{}{
		"status":  updateData.Status,
		"comment": updateData.Comment,
	}

	// 如果状态发生变化，更新处理时间
	if request.Status != updateData.Status {
		now := time.Now()
		updates["processed_at"] = &now
	}

	// 更新维修申请
	if err := database.DB.Model(&request).Updates(updates).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新维修申请失败"})
		return
	}

	// 重新获取更新后的数据
	database.DB.First(&request, id)
	c.JSON(http.StatusOK, request)
}

// DeleteRepairRequest 删除维修申请
func DeleteRepairRequest(c *gin.Context) {
	id := c.Param("id")
	var request models.RepairRequest

	// 检查维修申请是否存在
	if err := database.DB.First(&request, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "维修申请不存在"})
		return
	}

	// 只允许删除已完成或已驳回的维修申请
	if request.Status != models.StatusCompleted && request.Status != models.StatusRejected {
		c.JSON(http.StatusBadRequest, gin.H{"error": "只能删除已完成或已驳回的维修申请"})
		return
	}

	// 删除维修申请
	if err := database.DB.Delete(&request).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除维修申请失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "维修申请已删除"})
}
